from rctk.widgets.control import Control
from rctk.task import Task
from rctk.event import Event, dispatcher

class EndedEvent(Event):
    pass

dispatcher.register("ended", EndedEvent)

def quote(s):
    ## Quote a URL. urllib2.quote won't do because it will quote the http://
    ## part as well. Esp. # cause confusion on the client side.
    ## urlsplit won't help either, it'll split the #whatever part into a 
    ## fragment. Sample filename causing problems: 05.snowy_in_F#_minor.ogg

    return s.replace(' ', '%20').replace('#', '%23')

class AudioControl(Control):
    name = "audiocontrol"

    _ended_handler = None

    def _set_ended(self, val):
        self._ended_handler = val
        self.tk.queue(Task("Ended handler installed on %s %d" % (self.name, self.id), {"control":self.name, "id":self.id, "action":"handler", "type":"ended"}))

    def _get_ended(self):
        return self._ended_handler

    ended = property(_get_ended, _set_ended)

    ## api
    def load(self, url):
        self.tk.call(self, "load", quote(url))

    def play(self):
        self.tk.call(self, "play")

    def pause(self):
        self.tk.call(self, "pause")

